<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CFG Assistant</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }

        .header p {
            font-size: 1.2em;
            opacity: 0.9;
        }

        .main-content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
            padding: 30px;
        }

        .panel {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 25px;
            border: 1px solid #e9ecef;
        }

        .panel h3 {
            color: #495057;
            margin-bottom: 20px;
            font-size: 1.3em;
            border-bottom: 2px solid #007bff;
            padding-bottom: 10px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #495057;
        }

        select, textarea, input {
            width: 100%;
            padding: 12px;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.3s ease;
        }

        select:focus, textarea:focus, input:focus {
            outline: none;
            border-color: #007bff;
            box-shadow: 0 0 0 3px rgba(0,123,255,0.1);
        }

        textarea {
            resize: vertical;
            min-height: 150px;
            font-family: 'Courier New', monospace;
        }

        .btn {
            background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 16px;
            font-weight: 600;
            transition: all 0.3s ease;
            width: 100%;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,123,255,0.3);
        }

        .btn:disabled {
            background: #6c757d;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }

        .result-panel {
            grid-column: 1 / -1;
            margin-top: 20px;
        }

        .result-content {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 20px;
            min-height: 200px;
            font-family: 'Courier New', monospace;
            white-space: pre-wrap;
            overflow-x: auto;
        }

        .status {
            padding: 10px 15px;
            border-radius: 5px;
            margin-bottom: 15px;
            font-weight: 600;
        }

        .status.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .status.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .status.loading {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }

        .result-section {
            margin-top: 20px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 8px;
            border: 1px solid #e9ecef;
        }

        .result-section h4 {
            margin: 0 0 15px 0;
            color: #495057;
            font-size: 1.1em;
        }

        .code-display {
            background: #2d3748;
            color: #e2e8f0;
            padding: 15px;
            border-radius: 6px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            line-height: 1.4;
            max-height: 300px;
            overflow-y: auto;
            white-space: pre-wrap;
            word-wrap: break-word;
        }

        .image-display {
            background: white;
            padding: 15px;
            border-radius: 6px;
            border: 1px solid #dee2e6;
            text-align: center;
            min-height: 200px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .image-display img {
            max-width: 100%;
            max-height: 500px;
            border-radius: 4px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .image-display .placeholder {
            color: #6c757d;
            font-style: italic;
        }

        .node {
            fill: #007bff;
            stroke: #0056b3;
            stroke-width: 2px;
        }

        .edge {
            stroke: #6c757d;
            stroke-width: 2px;
            marker-end: url(#arrowhead);
        }

        .node-label {
            font-family: Arial, sans-serif;
            font-size: 12px;
            fill: white;
            text-anchor: middle;
            dominant-baseline: middle;
        }

        @media (max-width: 768px) {
            .main-content {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🔄 CFG Assistant</h1>
            <p>控制流图生成助手</p>
        </div>

        <div class="main-content">
            <div class="panel">
                <h3>📝 代码输入</h3>
                <div class="form-group">
                    <label for="language">编程语言:</label>
                    <select id="language">
                        <option value="Python">Python</option>
                        <option value="Java">Java</option>
                        <option value="C">C</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="code">源代码:</label>
                    <textarea id="code" placeholder="请输入您的代码...">def fibonacci(n):
    if n <= 1:
        return n
    else:
        return fibonacci(n-1) + fibonacci(n-2)

def main():
    n = 10
    result = fibonacci(n)
    print(f"Fibonacci({n}) = {result}")

if __name__ == "__main__":
    main()</textarea>
                </div>
                <button class="btn" onclick="generateCFG()">🚀 生成控制流图</button>
            </div>

            <div class="panel">
                <h3>⚙️ 模型配置</h3>
                <div class="form-group">
                    <label for="model">AI模型:</label>
                    <select id="model">
                        <option value="gpt-4">GPT-4</option>
                        <option value="gpt-4-turbo">GPT-4 Turbo</option>
                        <option value="gpt-3.5-turbo">GPT-3.5 Turbo</option>
                        <option value="deepseek-chat">DeepSeek Chat</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="client">客户端:</label>
                    <select id="client">
                        <option value="openai">OpenAI</option>
                        <option value="deepseek">DeepSeek</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="temperature">温度参数:</label>
                    <input type="range" id="temperature" min="0" max="2" step="0.1" value="0">
                    <span id="tempValue">0.0</span>
                </div>
                <button class="btn" onclick="testConnection()">🔗 测试连接</button>
            </div>

            <div class="panel result-panel">
                <h3>📊 结果展示</h3>
                <div id="status"></div>
                
                <!-- Graph Code 展示区域 -->
                <div class="result-section">
                    <h4>🔧 生成的 Graph Code</h4>
                    <div id="graphCode" class="code-display">等待生成结果...</div>
                </div>
                
                <!-- CFG 图片展示区域 -->
                <div class="result-section">
                    <h4>📈 CFG 控制流图</h4>
                    <div id="cfgImage" class="image-display">等待生成图片...</div>
                </div>
            </div>
        </div>
    </div>


    <script>
        const API_BASE = 'http://localhost:8000';

        // 温度参数滑块
        document.getElementById('temperature').addEventListener('input', function() {
            document.getElementById('tempValue').textContent = this.value;
        });

        // 显示状态
        function showStatus(message, type = 'loading') {
            const statusDiv = document.getElementById('status');
            statusDiv.className = `status ${type}`;
            statusDiv.textContent = message;
        }

        // 显示Graph Code
        function showGraphCode(graphCode) {
            const codeDisplay = document.getElementById('graphCode');
            if (graphCode) {
                codeDisplay.textContent = graphCode;
            } else {
                codeDisplay.innerHTML = '<span class="placeholder">未生成Graph Code</span>';
            }
        }

        // 显示CFG图片
        function showCFGImage(imageUrl) {
            const imageDisplay = document.getElementById('cfgImage');
            if (imageUrl) {
                console.log('显示CFG图片，URL:', imageUrl);
                
                // 确保URL是完整的
                const fullUrl = imageUrl.startsWith('http') ? imageUrl : `${API_BASE}${imageUrl}`;
                console.log('完整图片URL:', fullUrl);
                
                // 创建图片元素并添加详细错误处理
                const img = document.createElement('img');
                img.src = fullUrl;
                img.alt = 'CFG控制流图';
                img.style.maxWidth = '100%';
                img.style.height = 'auto';
                img.style.border = '1px solid #ccc';
                
                img.onload = function() {
                    console.log('✅ 图片加载成功:', fullUrl);
                    imageDisplay.innerHTML = '';
                    imageDisplay.appendChild(img);
                };
                
                img.onerror = function(e) {
                    console.error('❌ 图片加载失败:', fullUrl);
                    console.error('错误事件:', e);
                    
                    // 尝试通过fetch测试URL可访问性
                    fetch(fullUrl, { method: 'HEAD' })
                        .then(response => {
                            console.log('URL可访问性测试:', response.status, response.statusText);
                            console.log('Content-Type:', response.headers.get('content-type'));
                        })
                        .catch(fetchError => {
                            console.error('URL访问测试失败:', fetchError);
                        });
                    
                    imageDisplay.innerHTML = `
                        <div style="color: red; text-align: left;">
                            <strong>❌ 图片加载失败</strong><br>
                            URL: ${fullUrl}<br>
                            请检查:<br>
                            1. 图片URL是否正确<br>
                            2. 服务器是否正常运行<br>
                            3. 浏览器控制台是否有CORS错误<br>
                            4. 网络连接是否正常
                        </div>
                    `;
                };
                
                imageDisplay.innerHTML = '<span style="color: #666;">正在加载图片...</span>';
                
            } else {
                imageDisplay.innerHTML = '<span class="placeholder">未生成CFG图片</span>';
            }
        }

        // 测试连接
        async function testConnection() {
            showStatus('正在测试连接...', 'loading');
            
            try {
                const response = await fetch(`${API_BASE}/health`);
                const data = await response.json();
                
                if (response.ok) {
                    showStatus('✅ 连接成功！', 'success');
                    console.log('连接成功，服务器状态:', data);
                } else {
                    showStatus('❌ 连接失败', 'error');
                    console.error('连接失败:', data);
                }
            } catch (error) {
                showStatus('❌ 网络错误: ' + error.message, 'error');
                showGraphCode(null);
                showCFGImage(null);
                console.error('网络错误:', error);
            }
        }

        // 生成CFG
        async function generateCFG() {
            const code = document.getElementById('code').value;
            const language = document.getElementById('language').value;
            const model = document.getElementById('model').value;
            const client = document.getElementById('client').value;
            const temperature = parseFloat(document.getElementById('temperature').value);

            if (!code.trim()) {
                showStatus('❌ 请输入代码', 'error');
                return;
            }

            showStatus('🔄 正在生成控制流图...', 'loading');

            try {
                const response = await fetch(`${API_BASE}/api/cfg/generate`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        code: code,
                        language: language,
                        model_name: model,
                        client_name: client,
                        temperature: temperature
                    })
                });

                const data = await response.json();

                if (response.ok && data.success) {
                    showStatus('✅ 控制流图生成成功！', 'success');
                    
                    console.log('生成成功，完整响应数据:', data);
                    console.log('Graph Code:', data.graph_code);
                    console.log('Image URL:', data.image_url);
                    
                    // 确保图片URL是完整路径
                    let imageUrl = data.image_url;
                    if (imageUrl && !imageUrl.startsWith('http')) {
                        imageUrl = `${API_BASE}${imageUrl}`;
                        console.log('转换后的完整图片URL:', imageUrl);
                    }
                    
                    // 显示Graph Code
                    showGraphCode(data.graph_code);
                    
                    // 显示CFG图片
                    showCFGImage(imageUrl);
                    
                } else {
                    showStatus('❌ 生成失败: ' + (data.message || '未知错误'), 'error');
                    console.error('生成失败，响应数据:', data);
                    showGraphCode(null);
                    showCFGImage(null);
                }
            } catch (error) {
                showStatus('❌ 网络错误: ' + error.message, 'error');
                showGraphCode(null);
                showCFGImage(null);
                console.error('网络错误:', error);
            }
        }



        // 页面加载时测试连接
        window.addEventListener('load', testConnection);
    </script>
</body>
</html>